#include <QString>
#include <QTcpSocket>

#include "smtpinvoker.h"

SMTPInvoker::SMTPInvoker()
{
    socket = new QTcpSocket();
}

SMTPInvoker::~SMTPInvoker()
{
    delete socket;
}

int SMTPInvoker::Connect(QString server,unsigned short port)
{
    socket->connectToHost(server,port);
    if (!socket->waitForConnected())
    {
        qDebug("Could not connect.");
        return -1;
    }
    if (!socket->waitForReadyRead())
    {
        qDebug("Could not read.");
        return -1;
    }
    QString result = socket->readAll();
    qDebug(qPrintable(result));
    return execute(QString("HELO %1\r\n").arg("localhost"));
}

int SMTPInvoker::Login(QString username, QString password)
{
    execute("AUTH LOGIN\r\n");
    execute(QString("%1\r\n").arg(QString(username.toAscii().toBase64())));
    return execute(QString("%1\r\n").arg(QString(password.toAscii().toBase64())));
}

int SMTPInvoker::Send(QString from,QString to, QString subject ,QString text)
{
    execute(QString("MAIL FROM: <%1>\r\n").arg(from));
    execute(QString("RCPT TO: <%1>\r\n").arg(to));
    execute("DATA\r\n");
    return execute(QString("From: %1\r\nTo: %2\r\n"
                    "Subject: %3\r\n\r\n"
                    "%4"
                    "\r\n.\r\n").arg(from,to,subject,text));
}

int SMTPInvoker::Quit()
{
    return execute("QUIT\r\n");
}

int SMTPInvoker::execute(QString cmd,QString *output)
{
    if(socket->write(cmd.toAscii()) == cmd.size())
    {
        if (socket->waitForBytesWritten())
        {
            if (!socket->waitForReadyRead())
            {
                    qDebug("Could not read.");
                    return -1;
            }
            QString result = socket->readAll();
            qDebug(qPrintable(result));
            if(output != NULL)
            {
                *output = result;
            }
            bool hasReturn;
            int status = result.mid(0,3).toInt(&hasReturn);
            if(hasReturn)
            {
                return status;
            }
            else
            {
                return 0;
            }
        }
        else
        {
            qDebug("Could not write bytes from buffer.");
            return -1;
        }
    }
    else
    {
        qDebug("Could not write all bytes to server.");
        return -1;
    }
}
